<!--
 * @Author: 陈俊升 761723995@qq.com
 * @Date: 2024-02-26 16:18:09
 * @LastEditors: 陈俊升 761723995@qq.com
 * @LastEditTime: 2024-03-11 15:36:11
 * @FilePath: /hr_new_vue3/src/views/Management/Human/ChangeManagement/InductionManagement/EntryApplicationSetting/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!-- 入职申请设置 -->
<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew title="入职申请设置" showBack> </pageHeaderNew>
    </template>
    <div class="wrap">
      <a-collapse
        :default-active-key="['1']"
        :bordered="false"
        expand-icon-position="right"
        v-model:active-key="isCollapse"
      >
        <a-collapse-item key="1">
          <template #header>
            <div class="title-box">
              <div class="title">
                <div
                  :style="{
                    marginLeft: '25px'
                  }"
                >
                  <h3>入职申请步骤说明</h3>
                </div>
              </div>
            </div>
          </template>
          <template #extra>
            {{ isCollapse == '1' ? '收起' : '展开步骤说明' }}
          </template>
          <a-steps :current="0" style="padding: 0 40px">
            <a-step description="设置入职登记表信息">新建并设置入职申请</a-step>
            <a-step description="短信和邮件发送或者制作台卡现在扫码"
              >发送入职登记</a-step
            >
            <a-step description="员工扫码填写登记表并提交"
              >员工添加入职登记</a-step
            >
            <a-step description="HR审核员工填写登记表">审核入职登记</a-step>
          </a-steps>
        </a-collapse-item>
      </a-collapse>

      <section class="main">
        <div class="main-header">
          <div class="title-box">
            <div class="title">
              <div
                :style="{
                  marginLeft: '25px'
                }"
              >
                <h3>入职申请步骤说明</h3>
              </div>
            </div>
          </div>
          <a-space>
            <a-button type="outline" @click="goApplication(0, 1)"
              >新增入职申请</a-button
            >
            <a-button
              type="outline"
              status="danger"
              v-show="tableMode === 1"
              @click="delAll"
              >批量删除</a-button
            >
            <a-tooltip content="列表视图">
              <IconFont
                type="icon-liebiao2"
                :size="26"
                class="icon"
                @click="changeMode(1)"
                :class="{ iconActive: tableMode === 1 }"
              />
            </a-tooltip>
            <a-tooltip content="二维码视图"
              ><IconFont
                type="icon-tuxingliebiao-"
                :size="24"
                class="icon"
                @click="changeMode(2)"
                :class="{ iconActive: tableMode === 2 }"
              />
            </a-tooltip>
          </a-space>
        </div>
        <a-divider :margin="10" />

        <TableTurn
          :tableData="getTableData"
          :args="args"
          ref="tableRef"
          v-show="tableMode === 1"
          rowKey="id"
        >
          <a-table-column :width="80">
            <template #title> 序号 </template>
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column :width="150" title="方案名称" data-index="name">
          </a-table-column>
          <a-table-column
            :width="300"
            title="方案说明"
            data-index="description"
          >
          </a-table-column>
          <a-table-column :width="150" title="创建人" data-index="">
          </a-table-column>
          <a-table-column :width="150" title="创建时间" data-index="">
          </a-table-column>
          <a-table-column :width="120" title="操作" fixed="right">
            <template #cell="{ record }">
              <a-space :size="0">
                <a-tooltip content="入职邀请">
                  <icon-font
                    type="icon-ruzhiyaoqinghan"
                    :size="26"
                    :style="{
                      cursor: 'pointer'
                    }"
                    @click="goOffer(record)"
                  />
                </a-tooltip>
                <a-tooltip content="查看">
                  <icon-font
                    type="icon-details-def"
                    :size="26"
                    :style="{
                      cursor: 'pointer'
                    }"
                    @click="goApplication(record.id, 2)"
                  />
                </a-tooltip>
                <a-tooltip content="编辑">
                  <icon-font
                    type="icon-edit"
                    :size="26"
                    :style="{
                      cursor: 'pointer'
                    }"
                    @click="goApplication(record.id, 1)"
                  />
                </a-tooltip>

                <a-tooltip content="删除" v-if="record.isDefault !== 1">
                  <a-popconfirm
                    content="是否确认删除该条数据?"
                    @ok="del(record.id)"
                  >
                    <IconFont
                      type="icon-delete"
                      :size="26"
                      :style="{
                        cursor: 'pointer'
                      }"
                    />
                  </a-popconfirm>
                </a-tooltip>
              </a-space>
            </template>
          </a-table-column>
        </TableTurn>

        <section
          v-show="tableMode === 2"
          class="code-wrap"
          v-for="item in data"
          :key="item.id"
        >
          <div class="qrCode">
            <div :id="`qrCode${item.id}`">
              <VueQr
                ref="qrCode"
                :text="item.url"
                :logoScale="40"
                :size="150"
                :margin="10"
              />
            </div>

            <a-button
              type="outline"
              style="margin-top: 20px"
              @click="saveQrcode(item.id)"
              >保存二维码</a-button
            >
          </div>
          <div class="qrCode-info">
            <div class="qrCode-info-header">
              <a-space>
                <h3>{{ item.name }}</h3>
                <a-tag bordered v-if="item.isDefault === 1">默认</a-tag>
              </a-space>
              <a-space>
                <a-button type="text" @click="goApplication(item.id, 2)"
                  >查看</a-button
                >
                <a-button type="text" @click="goApplication(item.id, 1)"
                  >编辑</a-button
                >
              </a-space>
            </div>
            <span>说明：{{ item.description }} </span>
            <a-space>
              <h3>有效类型:</h3>
              <a-radio-group v-model="item.duration">
                <a-radio :value="-1">永久</a-radio>
                <a-radio :value="2">有效期</a-radio>
              </a-radio-group>
              <a-space v-show="item.duration === 2">
                <a-input-number
                  v-model="item.time"
                  placeholder="请输入有效天数"
                  hide-button
                  :min="1"
                  :precision="0"
                />天
              </a-space>
              <a-tooltip content="刷新链接">
                <IconFont
                  style="cursor: pointer"
                  :size="20"
                  type="icon-shuaxin"
                  @click="refreshLink(item)"
                ></IconFont>
              </a-tooltip>
            </a-space>
            <a-space :size="0">
              <a-input
                v-model="item.url"
                disabled
                :style="{ width: '600px' }"
              />
              <a-button type="primary" @click="copyLink(item.url)"
                >复制链接</a-button
              >
            </a-space>
          </div>
        </section>
      </section>
    </div>
  </ContentCard>
  <JobOfferModal v-model:visible="jobOfferVisible" :data="currData" />
</template>
<script setup lang="tsx">
import VueQr from 'vue-qr/src/packages/vue-qr.vue';
import {
  GetEntryApplicationSetting,
  DelEntryApplicationSetting,
  PutEntryApplicationSetting
} from '@/apis/management/human/humanChange/entry';
import { PostApplySign } from '@/apis/management/personnel/changeManagement/inductionManagement';
import JobOfferModal from './JobOfferModal/index.vue';
import { base64ToBlob } from '@/utils/utils';
import { Message, Modal } from '@arco-design/web-vue';

const router = useRouter();
let isCollapse = ref(['1']);

let currData = ref({}); // 储存当前保存的数据
let jobOfferVisible = ref(false); // 入职邀请弹出框
const goOffer = (record: any) => {
  currData.value = record;
  jobOfferVisible.value = true;
};

// 前往申请页面 type 1新增/编辑 2查看
const goApplication = (id: number, type: 1 | 2) => {
  router.push({
    name: 'EntryApplicationSettingAdd',
    query: {
      id,
      type
    }
  });
};

// 表格属性
const args = {
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
};
let tableMode = ref(2); // 表格的模式 1列表视图 2二维码视图

// 转换表格的模式
const changeMode = (mode: 1 | 2) => {
  tableMode.value = mode;
};

let tableRef = ref();
let data = ref([]); // 表格数据
// 获取列表数据
const getTableData = async (pageData?: any) => {
  try {
    const res = await GetEntryApplicationSetting({
      ...pageData
    });
    data.value = res.content;
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 删除
const del = async (id: number) => {
  try {
    await DelEntryApplicationSetting({
      ids: [id]
    });
    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};
const selectedList = computed(() => tableRef.value.selectedList); // 选中的数据
const selectedListData = computed(() => tableRef.value.selectedListData); // 选中的数据

const delAll = async () => {
  try {
    if (selectedList.value.length === 0) {
      Message.error('请至少选择一项');
      return;
    }
    Modal.open({
      title: '批量删除',
      content: '确定删除选中的数据吗？',
      onOk: async () => {
        const ind = selectedListData.value.findIndex(
          (el: any) => el.isDefault === 1
        );
        if (ind !== 1) {
          Message.error('默认模板不能被删除！请重新选择！');
          return;
        }
        await DelEntryApplicationSetting({
          ids: selectedList.value
        });
        refresh();
      }
    });
  } catch (error: unknown) {
    console.log(error);
  }
};

// 保存二维码
const saveQrcode = (id) => {
  //
  const fileName = `二维码${id}`;
  let img = document
    .getElementById(`qrCode${id}`)
    .getElementsByTagName('img')[0].src;
  let aLink = document.createElement('a');
  let blob = base64ToBlob(img);
  let evt = document.createEvent('HTMLEvents');
  evt.initEvent('click', true, true); // initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
  aLink.download = fileName;
  aLink.href = URL.createObjectURL(blob);
  aLink.click();
};

// 刷新链接
const refreshLink = async (record: any) => {
  try {
    if (record.duration === 2 && !record.time) {
      Message.error('请输入有效天数！');
      return;
    }
    const { sign, timeStamp } = await PostApplySign({
      duration: record.duration
    });
    record.url = `http://192.168.31.103:5173/entryApplicationInviteMobile?id=${record.id}&sign=${sign}&timeStamp=${timeStamp}`;
    await PutEntryApplicationSetting({
      ...record
    });
    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 复制链接
const copyLink = (url: string) => {
  navigator.clipboard.writeText(url).then(
    function () {
      /* 如果文本成功复制，显示一条消息来确认 */
      Message.success('复制成功！');
    },
    function (err) {
      /* 如果出现错误，显示一条错误消息 */
      Message.error('复制失败，请重试！');
    }
  );
};
const refresh = () => {
  tableRef.value.loadData();
};
</script>
<style lang="less" scoped>
.wrap {
  padding: 10px 20px;
  .title-box {
    position: relative;
    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 36px;
      border-radius: 4px;
      font-weight: 700;
    }
  }

  .title-box::before {
    position: absolute;
    // top: 33px;
    left: 10px;
    display: inline-block;
    height: 18px;
    top: 50%;
    transform: translateY(-50%);
    width: 10px;
    margin-right: 20px;
    border-radius: 2px;
    // transform: translateY(-50%);
    content: '';
    background-color: #165dff;
  }

  .main {
    margin-top: 20px;
    &-header {
      padding: 0 10px;
      display: flex;
      justify-content: space-between;
    }

    .code-wrap {
      border: 1px solid #eee;
      display: flex;
      .qrCode {
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding: 10px;
        border-right: 1px #dfddddee solid;
        margin-right: 20px;
      }
      .qrCode-info {
        flex: 1;
        display: flex;
        flex-direction: column;

        &-header {
          display: flex;
          justify-content: space-between;
        }
      }
      .qrCode-info > :nth-child(3) {
        margin-top: 30px;
      }
    }
  }
}

.icon {
  cursor: pointer;
}

.iconActive {
  color: #165dff;
}

:deep(.arco-collapse-item-content) {
  background-color: #fff;
}
:deep(.arco-tag) {
  background-color: #fff;
  color: #165dff;
  border-radius: 20px;
}
:deep(.arco-tag-bordered) {
  border-color: #165dff;
}
</style>
